package global_village.gui.utils;

import global_village.app.Utils;
import global_village.data.Group;

import java.net.URL;
import java.util.ArrayList;

import android.R.drawable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.global_village.app.R;

public class GroupsAdapter extends BaseAdapter{

	private static final String TAG = GroupsAdapter.class.getSimpleName();
	
	private Context ctx;
	private ArrayList<Group> groups;
	
	public GroupsAdapter(Context ctx , ArrayList<Group> groups){
		this.ctx = ctx;
		this.groups = groups;
	}
	
	public int getCount() {
		return groups.size();
	}

	public Group getItem(int position) {
		Log.i(TAG, "getItem()");
		return groups.get(position);
	}

	public long getItemId(int position) {
		//TODO - check for exception
		return Long.parseLong(groups.get(position).getId());
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		TextView groupItem;
		if(convertView == null){
			LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			groupItem = (TextView) li.inflate(R.layout.main_groups_item, parent ,false);
			
			GridView.LayoutParams params = new GridView.LayoutParams(100, 100);
			groupItem.setLayoutParams(params);
			
		}else{
			groupItem = (TextView) convertView;
		}
		
		String imgPath = "http://" + Utils.getSettingsByKey("serverIp") + "/img/" + groups.get(position).getImg();
		
		try{
			URL imgUrl = new URL(imgPath);
			Bitmap groupImg = BitmapFactory.decodeStream(imgUrl.openConnection().getInputStream());
			Drawable d = new BitmapDrawable(groupImg);
			groupItem.setCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
		}catch (Exception e) {
			groupItem.setCompoundDrawablesWithIntrinsicBounds(0, drawable.star_big_on, 0, 0);
		}
		groupItem.setText(groups.get(position).getName());
		
		return groupItem;
	}

}
